package com.getword.service.impl;

import com.getword.domain.Course;
import com.getword.domain.Grade;
import com.getword.mongodao.CourseRepository;
import com.getword.service.CourseService;
import com.getword.web.model.Result;
import com.getword.web.model.ResultCode;
import com.mongodb.client.result.UpdateResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.regex.Pattern;


@Service
//@Transactional(readOnly = false)
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseRepository courseRepository;
    @Autowired
    private MongoTemplate mongo;

    @Override
    public Result addCourse(Course course) {
        Course save = courseRepository.save(course);
        return Result.success(save, null);
    }

    @Override
    public Result getCourseByName(String key) {
        if (StringUtils.isEmpty(key)) {
            return Result.fail(ResultCode.PARAM_IS_INVALID.getCode(), "关键字为空", null);
        }
        Pattern pattern = Pattern.compile("^.*" + key + ".*$", Pattern.CASE_INSENSITIVE);
        Query query = Query.query(Criteria.where("name").regex(pattern));
        query.limit(20);
        List<Course> courses = mongo.find(query, Course.class);
        return Result.success(courses, null);
    }

    @Override
    public Result getCourseByNameAndGrade(String key, Long gradeId) {
        if (StringUtils.isEmpty(key)) {
            return Result.fail(ResultCode.PARAM_IS_INVALID.getCode(), "关键字为空", null);
        }
        if (gradeId==null||gradeId==0) {
            return getCourseByName(key);
        }
        Pattern pattern = Pattern.compile("^.*" + key + ".*$", Pattern.CASE_INSENSITIVE);

        Query query = Query.query(Criteria.where("name").regex(pattern).and("grade").is(new Grade(gradeId)));
        query.limit(20);
        List<Course> courses = mongo.find(query, Course.class);
        return Result.success(courses, null);
    }

    @Override
    public Result getCoursesByGradeId(Long gradeId) {
        Grade grade = null;
        if(gradeId!=null&&gradeId!=0){
            grade = new Grade(gradeId);
        }
//        List<Course> courses = courseRepository.findCourseByGrade(grade);
        Criteria where = new Criteria();
        if(grade!=null){
            where.where("grade").is(grade);
        }
        Query query = Query.query(where).limit(20);
        List<Course> courses = mongo.find(query, Course.class);
        return Result.success(courses);
    }

    @Override
    public Result getCount(Course course) {
        // 条件 {grade.id, name}
        Criteria where = new Criteria();
        if(course.getGrade()!=null){
            where.where("grade").is(course.getGrade());
        }
        if(StringUtils.isNotBlank(course.getName())){
            where.and("name").regex(Pattern.compile(".*"+course.getName()+".*", Pattern.CASE_INSENSITIVE));
        }

        long count = mongo.count(Query.query(where), Course.class);
        return Result.success(count);
    }

    @Override
    public Result getCourses(Pageable pageable, Course course) {
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true) //改变默认大小写忽略方式：忽略大小写
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                .withIgnorePaths("id"); //采用“包含匹配”的方式查询
        Example<Course> example = Example.of(course, matcher);
        Page<Course> data = courseRepository.findAll(example, pageable);
        Page<Course> all = courseRepository.findAll(example, pageable);
        return Result.success(all);
    }

    @Override
    public Result updateCourse(Course course) {
        // {name,desc}
        if(course.getId()<1){
            return Result.fail("课程ID不存在");
        }
        Query query = Query.query(Criteria.where("id").is(course.getId()));
        Update update = new Update();
        if(StringUtils.isNotBlank(course.getName()))
            update.update("name", course.getName());
        if(StringUtils.isNotBlank(course.getDesc()))
            update.set("desc", course.getDesc());
        UpdateResult result = mongo.updateFirst(query, update, Course.class);
        if(result.getModifiedCount()>0){
            return Result.success(result);
        }
        return Result.fail("未做修改");
    }
}
